package com.ele.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ele.pojo.*;
import com.ele.service.CartService;
import com.ele.service.FoodService;
import com.ele.service.OrderdetailetService;
import com.ele.service.OrdersService;
import com.ele.mapper.OrdersMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author qubo
 * @description 针对表【orders】的数据库操作Service实现
 * @createDate 2024-04-12 14:29:39
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
        implements OrdersService{
    @Resource
    private CartService cartService;
    @Resource
    private OrderdetailetService orderdetailetService;
    @Resource
    private FoodService foodService;
    @Override
    @Transactional // 使用spring的注解控制事务
    public ResponseData<Orders> addOrder(OrderVO orderVO) {
        ResponseData<Orders> responseData = new ResponseData<Orders>();
        Orders order = new Orders();
        // 生成订单的时间
        order.setOrderDate(new Date());
        // 订单的状态：应该是待支付
        order.setOrderState(0);
        // 设置订单对应的收货地址ID
        order.setDaId( Integer.parseInt( orderVO.getDaId() ) );
        // 设置订单对应的下单人的id
        order.setUserId(orderVO.getUserId());
        // 根据购物车id查询购物车中的商品等信息
        ResponseData<Cart> checkCart = this.cartService.getCheckCart(orderVO.getCartId());
        List<Cart> datas = checkCart.getDatas();
        // 计算总金额
        Double total = 0.0;
        for (Cart data : datas) {
            total = total + data.getQuantity() * data.getFood().getFoodPrice();
            order.setBusinessId(data.getBusinessId());
        }
        order.setOrderTotal(BigDecimal.valueOf(total));
        // 1、给订单表中添加订单数据（购物车中的多个菜品信息，最终一次提交，只生成一条订单记录）
        boolean save = this.save(order);
        if(save){
            // 2、根据订单的信息，需要将订单中的菜品信息，添加到订单明细表中
            for (Cart data : datas) {
                Orderdetailet orderdetailet = new Orderdetailet();
                // 设置订单明细表中的菜品id
                orderdetailet.setFoodId(data.getFoodId());
                // 设置当前订单明细所属的订单的id
                orderdetailet.setOrderId(order.getOrderId());
                // 设置当前订单明细所属的菜品的数据量
                orderdetailet.setQuantity(data.getQuantity());
                // 保存明细
                this.orderdetailetService.save(orderdetailet);
            }
            // 需要删除购物车中的对应的数据
            this.cartService.deleteCartByIds(orderVO.getCartId());
            responseData.setCode(20000);
            responseData.setMessage("订单添加成功");
            responseData.setData(order);
        }else{
            responseData.setCode(50000);
            responseData.setMessage("订单添加失败");
        }
        return responseData;
    }

    @Override
    public void updateOrderState(String tradeNo) {
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<Orders>();
        wrapper.eq(Orders::getOrderId,tradeNo).set(Orders::getOrderState,1);
        this.update(wrapper);
    }

    @Override
    public ResponseData<Orders> getOrderList(String userId) {
        ResponseData<Orders> responseData = new ResponseData<Orders>();
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<Orders>();
        wrapper.eq(Orders::getUserId,userId);
        List<Orders> orders = this.list(wrapper);
        if(orders!=null && orders.size()>0){
            // 需要根据订单查询明细，同时查询菜品信息
            for (Orders order : orders) {
                // 根据订单id查询订单明细
                LambdaUpdateWrapper<Orderdetailet> wrapper1 = new LambdaUpdateWrapper<>();
                wrapper1.eq(Orderdetailet::getOrderId,order.getOrderId());
                List<Orderdetailet> orderdetailets = this.orderdetailetService.list(wrapper1);
                // 根据订单明细中的菜品id查询菜品信息
                for (Orderdetailet orderdetailet : orderdetailets) {
                    LambdaUpdateWrapper<Food> wrapper2 = new LambdaUpdateWrapper<>();
                    wrapper2.eq(Food::getFoodId,orderdetailet.getFoodId());
                    Food food = this.foodService.getOne(wrapper2);
                    orderdetailet.setFood(food);
                }
                order.setOrderdetailet(orderdetailets);
            }
            responseData.setCode(20000);
            responseData.setDatas(orders);
        }else{
            responseData.setCode(50000);
            responseData.setMessage("没有查询到订单信息");
        }
        return responseData;
    }

}